package top.yehot.kettle.boot.core.task;

import java.time.LocalDateTime;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.listeners.JobListenerSupport;

import top.yehot.cmm.util.core.utils.StrUtil;
import top.yehot.cmm.util.spring.utils.SpringUtil;
import top.yehot.kettle.boot.core.SysConst;
import top.yehot.kettle.boot.core.config.KettleCfg;
import top.yehot.kettle.boot.core.utils.FileUtil;
import top.yehot.kettle.boot.enums.TaskRecordStatusEnum;
import top.yehot.kettle.boot.models.entity.TaskRecord;
import top.yehot.kettle.boot.service.TaskRecordService;

public class KettleJobListener extends JobListenerSupport {

	@Override
	public String getName() {
		return "kettleJobListener";
	}

	// 开始执行任务前
	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		super.jobToBeExecuted(context);

		// 获取TaskRecordService
		TaskRecordService taskRecordService = SpringUtil.getBean(TaskRecordService.class);
		// 获取JobDataMap
		JobDataMap jobData = context.getJobDetail().getJobDataMap();

		// 生成uuid
		String uuid = StrUtil.uuid();
		// 任务ID
		int taskId = jobData.getInt(SysConst.TASK_ID);

		// 设置日志文件路径
		String baseLogPath = FileUtil.removeEndSlash(KettleCfg.logFilePath);
		String logFilePath = baseLogPath + FileUtil.separator + taskId + "-" + uuid + ".log";

		TaskRecord tr = new TaskRecord()
				.setId(uuid).setTaskId(taskId).setStartTime(LocalDateTime.now())
				.setRecordStatus(TaskRecordStatusEnum.W).setLogFilePath(logFilePath);
		taskRecordService.save(tr);

		// 设置值
		jobData.put(SysConst.TASK_LOG, logFilePath);
		jobData.put(SysConst.TASK_RECORD_ID, uuid);
	}

	// 结束任务后
	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
		super.jobWasExecuted(context, jobException);
		// 获取TaskRecordService
		TaskRecordService taskRecordService = SpringUtil.getBean(TaskRecordService.class);
		// 获取JobDataMap
		JobDataMap jobData = context.getJobDetail().getJobDataMap();
		
		// 任务ID
		String taskRecordId = jobData.getString(SysConst.TASK_RECORD_ID);

		TaskRecord tr = new TaskRecord()
				.setId(taskRecordId).setStopTime(LocalDateTime.now());
		if (null != jobException) {
			tr.setRecordStatus(TaskRecordStatusEnum.N);
		} else {
			tr.setRecordStatus(TaskRecordStatusEnum.Y);
		}
		taskRecordService.updateById(tr);
	}

}
